package view;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.AbstractTableModel;

import dao.MenuDao;
import dao.OrdersDao;
import modle.Country;
import modle.Menu;
import util.DbUtil;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.awt.Color;
import javax.swing.JTable;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import java.awt.Toolkit;
import javax.swing.JScrollPane;
import javax.swing.JButton;

public class Bill extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private JLabel lblNewLabel_1;
	private JLabel Test1;
	private JLabel Test2;
	private JLabel Test3;
	private static String s = new String();
	private static Object[][] rowData = new Object[20][20];
	private static Map<String, String> map = null;
	private JComboBox comboBox;
	private List<Country> listCountries;
	private Locale locale;
	ResourceBundle rd;
	private JLabel backgroundlabel;
	private JScrollPane scrollPane;
	private JTable table_1;
	private JButton btnPay;
	private int Id;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Bill frame = new Bill(1, null);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 * @param map 
	 */
	public Bill(int id, Map<String, String> m) {
		
		Id = id;
		
		setTitle("Welcome to Food Corner");
		setIconImage(Toolkit.getDefaultToolkit().getImage(Bill.class.getResource("/img/iconImage.jpg")));
		if(m==null)   return;
		map = m;
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 651, 547);
		contentPane = new JPanel();
		
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));	//边界设置为5个像素
		setContentPane(contentPane);						//将jpanel面板放在frame框架上
		contentPane.setLayout(null);
		
		scrollPane = new JScrollPane();
		scrollPane.setBounds(89, 116, 465, 231);
		contentPane.add(scrollPane);
		
		table = new JTable(new MyTableModel());
		table.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		table.setBounds(91, 131, 446, 206);
		table.getTableHeader().setBounds(91, 101, 446, 30);
		contentPane.add(table.getTableHeader());
//		contentPane.add(table);
		table.getTableHeader().setSize(30, 30);
		table.setRowHeight(30);										//设置table行高
		scrollPane.setViewportView(table);
		
		lblNewLabel_1 = new JLabel("");
		lblNewLabel_1.setIcon(new ImageIcon(Bill.class.getResource("/img/pay2.png")));
		lblNewLabel_1.setBounds(218, 17, 72, 65);
		contentPane.add(lblNewLabel_1);
		
		Test1 = new JLabel("1111");
		Test1.setForeground(new Color(95, 158, 160));
		Test1.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		Test1.setBounds(121, 361, 287, 47);
		contentPane.add(Test1);
		
		Test2 = new JLabel("2222");
		Test2.setForeground(new Color(100, 149, 237));
		Test2.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		Test2.setBounds(121, 421, 475, 47);
		contentPane.add(Test2);
		
		Test3 = new JLabel("New label");
		Test3.setForeground(new Color(95, 158, 160));
		Test3.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 21));
		Test3.setBounds(408, 358, 72, 52);
		contentPane.add(Test3);
		
		Test1.setText("You Bill for Your Order = ");
		Test3.setText(s + ".");
		Test2.setText("\"Thank You for Visiting Us !\"");
		
		comboBox = new JComboBox<>();						//组合按钮或可编辑字段和下拉列表的组件
		comboBox.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 17));
		comboBox.addItemListener(new ItemListener() {		//用于接收项目事件的侦听器接口。
			public void itemStateChanged(ItemEvent e) {
				int index = comboBox.getSelectedIndex();	//返回列表中与给定项目匹配的第一个项目。 
					String arr[] = listCountries.get(index).getId().split("-");					//  ???（应该是遇见 - 就分割）
					locale = new Locale(arr[0], arr[1]);//	???   Locale对象代表具体的地理，政治或文化地区。（第一个是语言，第二个是国家）
					rd = ResourceBundle.getBundle("resources.content", locale);		//使用指定的基本名称，区域设置和类加载器获取资源包（这里好像没用类加载器）。 
					
					//rd到底有什么用
					
					try {
						changeLanguage();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
			}
		});
		comboBox.setBounds(520, 17, 98, 32);
		contentPane.add(comboBox);
		
		btnPay = new JButton("Pay");
		btnPay.setBackground(new Color(176, 196, 222));
		btnPay.setFont(new Font("微软雅黑", Font.BOLD, 21));
		btnPay.setForeground(new Color(205, 92, 92));
		btnPay.setBounds(289, 30, 98, 40);
		contentPane.add(btnPay);
		btnPay.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Pay();
			}
		});
		
		fillCountries();
	}
	
	protected void Pay() {
		// TODO Auto-generated method stub
		Connection con = null;
		DbUtil dbUtil = new DbUtil();
		try{
			con = dbUtil.getCon();
			int num = OrdersDao.OrdersAdd(con, Id);
			if(num>0) {
				//弹出提示信息
				JOptionPane.showMessageDialog(null, "您的订单已提交，请耐心等待收货！");
				new Customer_Menu(Id).setVisible(true);
				this.dispose();
			}else {
				//弹出提示信息
				JOptionPane.showMessageDialog(null, "订单提交失败，请重新尝试！");
			}
		}catch(Exception e1){
			JOptionPane.showMessageDialog(null, "出现异常，订单提交失败！");
			e1.printStackTrace();
		}finally {
			try {
				// 关闭数据库连接
				dbUtil.closeCon(con);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}

	private ImageIcon ResizeImage(String imgpath, JLabel label) {
		// TODO Auto-generated method stub
		ImageIcon img1 = new ImageIcon(Bill.class.getResource(imgpath));
		Image img2 = img1.getImage();
		Image img3 = img2.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
		ImageIcon img4 = new ImageIcon(img3);
		return img4;
	}
	
	public static class MyTableModel extends AbstractTableModel {
        /**
         * 表头（列名）
         */
        private Object[] columnNames = {"菜品编号", "菜品名称", "菜品数量", "菜品单价"};

        /**
         * 表格所有行数据
         */
//        private Object[][] rowData = {
//                {"张三", 80, 80, 80},
//                {"John", 70, 80, 90},
//                {"Sue", 70, 70, 70},
//                {"Jane", 80, 70, 60},
//                {"Joe", 80, 70, 60}
//        };
        
        
//        
//        rowData = new Object[3][3];
        
        
        public MyTableModel() {
        	Menu menu = null;
        	
        	int n = map.size();
        	int num = 0;
        	
        	Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                System.out.println(key + "　：" + map.get(key));
                try {
					menu = MenuDao.MenuSearch3(DbUtil.getCon(), key);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                
                rowData[num][1] = key;
                rowData[num][2] = to_num(map.get(key));
                String s = menu.getPrice();
                
                rowData[num][3] = to_num(s);
                
                num++;
            }
            
            for(int i=0; i<n; ++i)
        	{
        		rowData[i][0] = i+1;
        	}
        	
        	rowData[n][2] = "Total";
        	int sum = 0;
        	for(int i=0; i<n; ++i)
	        	sum += (int)rowData[i][2]*(int)rowData[i][3];
        	rowData[n][3] = sum + " ￥";
        	
        	s = (String)rowData[n][3];
        }
        

        private int to_num(String s) {
			// TODO Auto-generated method stub
        	int num = 0;
        	for(int i=0; i<s.length(); ++i)
            	if(s.charAt(i)>='0' && s.charAt(i)<='9')   num = num*10 + (s.charAt(i)-'0');
        	
			return num;
		}


		/**
         * 返回总行数
         */
        @Override
        public int getRowCount() {
            return map.size()+1;
        }

        /**
         * 返回总列数
         */
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        /**
         * 返回列名称（表头名称），AbstractTableModel 中对该方法的实现默认是以
         * 大写字母 A 开始作为列名显示，所以这里需要重写该方法返回我们需要的列名。
         */
        @Override
        public String getColumnName(int column) {
            return columnNames[column].toString();
        }

        /**
         * 返回指定单元格的显示的值
         */
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return rowData[rowIndex][columnIndex];
        }
    }
	
	private void fillCountries() {
		// TODO Auto-generated method stub
		listCountries = new ArrayList<Country>();
		listCountries.add(new Country("en-US", "English"));
		listCountries.add(new Country("zh-CN", "中文"));
		
		for(Country c : listCountries)
			comboBox.addItem(c.getName());
	}

	protected void changeLanguage() {
		// TODO Auto-generated method stub
		
		/*
		 * billLabel=Bill for Your Order
			Test1= You Bill for Your Order = 
			Test2=\"Thank You for Visiting Us !\"
		 */
		
//		billLabel.setText(rd.getString("billLabel"));
		Test1.setText(rd.getString("Test1"));
		Test2.setText(rd.getString("Test2"));
	}
}
